<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"

      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-show="progressshow" type="circle" :percentage="percent" class="progress" />
    </el-upload>
  </div>

</template>

<script>
const COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDPecLo0vviGZdS1LPDm6AyWoqc9QTGp8B',
  SecretKey: 'pOima8RUHp8C1bv0pOindDXcR0JMAk5A'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percent: 0,
      progressshow: false
    }
  },

  methods: {
    // 自定义上传
    upload(res) {
      if (res.file) {
        this.progressshow = true
        cos.putObject({
          Bucket: 'kk-1306621526', // 存储桶的名称，必须
          Region: 'ap-nanjing', // 存储桶所在地域，必须字段
          Key: res.file.name, // 文件名，必须
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          // 上传进度条
          onProgress: function(progressData) {
            // console.log(JSON.stringify(progressData.percent))
            this.percent = progressData.percent
          }
        }, (err, data) => {
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            this.progressshow = false
          }
        })
      }
    },

    // 上传成功之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }

}

</script>

<style lang="scss">
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
